

init = function() {

	pin = document.getElementById("phonePin").value;
	log("pin="+pin+" Initializing "+pin);
	
	document.addEventListener(
		'touchstart', function(event) {
			if (event.touches[0].pageX < 100) {
				document.getElementById('arrowDown').style.display='inline';
			}
			if (event.touches[0].pageX > 200) {
				document.getElementById('arrowUp').style.display='inline';
			}
		}, false
	);
	
	// Position Variables
	var x = 0;
	var y = 0;
 
	// Speed - Velocity
	var vx = 0;
	var vy = 0;
 
	// Acceleration
	var ax = 0;
	var ay = 0;
	var az = 0;
 
	var delay = 1;
	var vMultiplier = 0.01;
	var clearToSend = 0;
	var msExpDelay = 1000; //message expiration
	var msDelay = 100; //delay after message received call back
	var timeToLive = 1000; //time tilt messages will live
	var lrtiltThreshold = 5;
	var udtiltThreshold = 2;
	 
    // establish sockets connection

	var connection = null;
	var producer = null;
	var topic = null;
	lastMsg = "";
	
	try {
		// Tracer.setTrace(true);
		log("Initializing Sockets");
		JMS_URL = "ws://demo.kaazing.com:80/jms";
		log("Connecting to "+JMS_URL);
		// console.log(stompConnectionFactory);
		stompConnectionFactory = new StompConnectionFactory(JMS_URL);
		log("Created StompConnectionFactory, creating connection...");
		var connectionFuture = stompConnectionFactory.createConnection(
			function () {
				if (!connectionFuture.exception) {
					log("CONNECTED");
					connection = connectionFuture.getValue();
					connection.setExceptionListener(handleException);
			
					session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			
					//log("Creating topic: /topic/destination");
					topic = session.createTopic("/topic/"+pin);
					log("Connected to /topic/"+pin);
					//consumer = session.createConsumer(topic);
					//consumer.setMessageListener(handleMessage);
			
					connection.start(function () { log("Connection Started..."); });
					log("creating producer")
				    producer = session.createProducer(topic);
					producer.setTimeToLive(timeToLive);
				    log("Load device motion handler:");
				    // log("deviceMotionHandler= "+deviceMotionHandler);
				    window.ondeviceorientation = deviceMotionHandler;
					clearToSend=1;
					log("Initialization Complete");
				}
				else {
					handleException(connectionFuture.exception);
				}
			}
		);
	}
	catch (e) {
		handleException(e);
	} 
  
 
	if (window.DeviceMotionEvent==undefined) {
		document.getElementById("noMotion").style.display="block";
		document.getElementById("yesMotion").style.display="none";
 
	}	
	
	deviceMotionHandler = function(event) {
//		ax = event.accelerationIncludingGravity.x;
//		ay = event.accelerationIncludingGravity.y;
		ax = event.alpha;
		ay = event.beta;
		az = event.gamma;

		
		logMsg("Detected Motion: x="+ax+" y="+ay+" z="+az);
        
        if (az > lrtiltThreshold){
        	Left = 0;
        	Right = 1;
        }
        else if (az < -lrtiltThreshold) {
        	Left = 1;
        	Right = 0;          	
        }
        else {
       		Left = 0;
        	Right = 0;            	            	
        }

        if (ay > udtiltThreshold){
        	Up = 0;
        	Down = 1;
        }
        else if (ay < -udtiltThreshold) {
         	Up = 1;
        	Down = 0;
        }
        else {
        	Up = 0;
        	Down = 0;
        }  
		
		if (clearToSend==1){
			try {
				logMsg("Move: Left="+Left+" & Right="+Right+" & Up="+Up+" & Down="+Down);
				var msg = session.createTextMessage(Left+"&"+Up+"&"+Right+"&"+Down);
				// msg.setJMSCorrelationID("1234");
				var expiration = new Date().getTime()+2000;
				msg.setJMSExpiration(expiration);
				msg.setJMSPriority(9);
				clearToSend=0;
				// producer.send(msg, function(){console.log("SENT"); setTimeout(function(){clearToSend=1;},msDelay);});
				producer.send(msg, function(){
					// console.log("SENT");
					setTimeout(function(){
						clearToSend=1;
						// console.log("got callback");						
					},msDelay);
				 });
			}
			catch (e) {
				handleException("Tried to send message: "+e);
			}
		}
		else {
			// log("Message queue is busy, dropping message");
		}




	}
 
	setInterval(function() {
		vy = vy + -(ay);
		vx = vx + ax;
 
		var ball = document.getElementById("ball");
		y = parseInt(y + vy * vMultiplier);
		x = parseInt(x + vx * vMultiplier);
		
		if (x<0) { x = 0; vx = 0; }
		if (y<0) { y = 0; vy = 0; }
		if (x>document.documentElement.clientWidth-20) { x = document.documentElement.clientWidth-20; vx = 0; }
		if (y>document.documentElement.clientHeight-20) { y = document.documentElement.clientHeight-20; vy = 0; }
		
		ball.style.top = y + "px";
		ball.style.left = x + "px";
		
		document.getElementById("wheelImg").src="images/wheel"+parseInt(ax)+".jpg";
	}, delay);
} 
 
 
function handleMessage(message) {
    	
	// setup the mapping for catching sockets joystick moves
    log(message.getText()+" "+message.getJMSDestination().getTopicName()+" "+message.getJMSCorrelationID()+" "+message.getJMSPriority());
}
 
function sendMessage() {
    try {
	    // var producer = session.createProducer(topic);
        var msg = session.createTextMessage("1&0&0&0");
        msg.setJMSCorrelationID("1234");
        msg.setJMSPriority(9);
        producer.send(msg, function(){clearToSend=1;log("got callback");});
    }
    catch (e) {
        handleException(e);
    }
}

 
function handleException(e) {
    console.log("EXCEPTION: "+e);
}

function log(logMsg) {
	var elem = document.getElementById("log");
	elem.innerHTML=elem.innerHTML+"\n"+logMsg;
}

function logMsg(logMsg) {
	var elem = document.getElementById("joystickMsg");
	elem.innerHTML=logMsg+"\n"+lastMsg;
	lastMsg=logMsg;
}
